import axios from '@/uni_modules/axios/index.js'
import md5 from '@/uni_modules/js-md5/build/md5.min.js';
import store from '@/store'
import commonConstants from '@/common/constants/commonConstants.js'
import stringUtils from '@/common/utils/stringUtils.js'
import requestUrl from '@/common/constants/requestUrl.js'
import {
	encrypt,
	decrypt
} from '@/common/js/des.js'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建axios实例
const service = axios.create({
	baseURL: commonConstants.request.resourceUrl,
	timeout: 20000, // 请求超时时间
	headers: {
		"X-Requested-With": "XMLHttpRequest",
		"Content-Type": "application/json;"
	}
})

// request interceptor
service.interceptors.request.use(
	config => {
		
		var token = decrypt(uni.getStorageSync("token"), 3)
		console.log("token:",token);
		if (token) {
			config.headers['Authorization'] = token
		}
		return config
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

//响应拦截器
service.interceptors.response.use(res => {
	return res
}, error => {
	return Promise.reject(error)
})
// 自定义适配器 ， 适配uniapp语法
// axios.defaults.adapter = function(config) {
// 	return new Promise((resolve, reject) => {
// 		let settle = require('axios/lib/core/settle');
// 		let buildURL = require('axios/lib/helpers/buildURL');
// 		uni.request({
// 			method: config.method.toUpperCase(),
// 			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
// 			header: config.headers,
// 			data: config.data,
// 			dataType: config.dataType,
// 			responseType: config.responseType,
// 			sslVerify: config.sslVerify,
// 			complete: function complete(response) {
// 				response = {
// 					data: response.data,
// 					status: response.statusCode,
// 					errMsg: response.errMsg,
// 					header: response.header,
// 					config: config
// 				};
// 				settle(resolve, reject, response);
// 			},
// 		});
// 	})
// }

export default {
	/**
	 * 根据条件获取分页结果
	 * @param {Object} url
	 * @param {Object} method
	 * @param {Object} param
	 * @param {Object} pager
	 * @param {Object} error
	 * @param {Object} success
	 */
	getListByPager: function(url, param, pager, success, error) {

		console.log("进入getListByCondition " + url);
		url += "?limit=" + pager.limit + (pager.page ? "&page=" + pager.page : "") + (pager.offset ? "&offset=" +
			pager.offset : "");
		if (stringUtils.isNotNullOrEmpty(pager.order)) {
			url += "&order=" + pager.order;
		}
		if (stringUtils.isNotNullOrEmpty(pager.sort)) {
			url += "&sort=" + pager.sort;
		}
		return this.request(url, "post", param, (res) => {

			if (success) {
				return success(res.data);
			} else {
				if (res.data.success) {
					if (res.data.hasData) {
						return res.data.data;
					}
				} else {
					if (res.data.msg && res.data.msg.length > 15) {
						uni.showModal({
							content: res.data.msg,
							showCancel: false
						});
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: "none"
						})
					}
				}
			}
		}, error);
	},
	/**
	 * 根据条件获取结果
	 * @param {Object} url
	 * @param {Object} method
	 * @param {Object} param
	 * @param {Object} error
	 * @param {Object} success
	 */
	getListByCondition: function(url, param, success, error) {

		console.log("进入getListByCondition " + url);

		return this.request(url, "post", param, (res) => {
			// console.log("getListByCondition 返回值" , JSON.stringify(res.data));

			if (success) {

				return success(res.data);
			} else {

				if (res.data.success) {

					if (res.data.hasData) {

						return res.data.list;

					}
				} else {
					if (res.data.msg && res.data.msg.length > 15) {
						uni.showModal({
							content: res.data.msg,
							showCancel: false
						});
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: "none"
						})
					}
				}
			}
		}, error);
	},
	/**
	 * 根据条件获取结果
	 * @param {Object} url
	 * @param {Object} method
	 * @param {Object} param
	 * @param {Object} error
	 * @param {Object} success
	 */
	getInfoByCondition: function(url, param, success, error) {

		console.log("进入getInfoByCondition ：" + url);
		return this.request(url, "post", param, (res) => {
			if (success) {

				return success(res.data);
			} else {

				if (res.data.success) {

					if (res.data.hasData) {

						console.log("getInfoByCondition 返回请求结果：" + res.data.data);
						return res.data.data;
					}
				} else {
					if (res.data.msg && res.data.msg.length > 15) {
						uni.showModal({
							content: res.data.msg,
							showCancel: false
						});
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: "none"
						})
					}
				}
			}
		}, error);
	},
	/**
	 * 删除
	 * @param {Object} url
	 * @param {Object} method
	 * @param {Object} param
	 * @param {Object} error
	 * @param {Object} success
	 */
	delete: function(url, param, success, error) {

		console.log("进入delete ：" + url);
		return this.request(url, "post", param, (res) => {

			if (success) {

				return success(res);
			} else {
				if (res.data.msg && res.data.msg.length > 15) {
					uni.showModal({
						content: res.data.msg,
						showCancel: false
					});
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: "none"
					})
				}
			}
		});
	},
	/**
	 * 更新数据状态
	 * @param {Object} url
	 * @param {Object} method
	 * @param {Object} param
	 * @param {Object} error
	 * @param {Object} success
	 */
	updateEnable: function(url, param, success, error) {

		console.log("进入delete ：" + url);
		return this.request(url, "post", param, (res) => {

			if (success) {

				return success(res);
			} else {
				if (res.data.msg && res.data.msg.length > 15) {
					uni.showModal({
						content: res.data.msg,
						showCancel: false
					});
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: "none"
					})
				}
			}
		});
	},
	/**
	 * 插入
	 * @param {Object} url
	 * @param {Object} method
	 * @param {Object} param
	 * @param {Object} error
	 * @param {Object} success
	 */
	insert: function(url, param, success, error) {

		console.log("进入insert ：" + url);
		return this.request(url, "post", param, (res) => {

			if (success) {

				return success(res);
			} else {

				if (res.data.success) {

					if (res.data.msg && res.data.msg.length > 15) {
						uni.showModal({
							content: res.data.msg,
							showCancel: false
						});
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: "none"
						})
					}
				} else {
					if (error) {
						return error(res)
					} else {
						if (res.data.msg && res.data.msg.length > 15) {
							uni.showModal({
								content: res.data.msg,
								showCancel: false
							});
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: "none"
							})
						}
					}
				}
			}
			return res.data;
		});
	},
	/**
	 * 更新
	 * @param {Object} url
	 * @param {Object} method
	 * @param {Object} param
	 * @param {Object} error
	 * @param {Object} success
	 */
	update: function(url, param, success, error) {

		console.log("进入update ：" + url);
		return this.request(url, "post", param, (res) => {

			if (success) {

				return success(res);
			} else {

				if (res.data.success) {
					if (res.data.msg && res.data.msg.length > 15) {
						uni.showModal({
							content: res.data.msg,
							showCancel: false
						});
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: "none"
						})
					}
				} else {
					if (error) {
						return error(res)
					} else {
						if (res.data.msg && res.data.msg.length > 15) {
							uni.showModal({
								content: res.data.msg,
								showCancel: false
							});
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: "none"
							})
						}
					}
				}
			}
			return res.data;
		});
	},

	/**
	 * 根据条件获取分页结果
	 * @param {Object} url
	 * @param {Object} method
	 * @param {Object} param
	 * @param {Object} pager
	 * @param {Object} error
	 * @param {Object} success
	 */
	exportExcel: function(url, param, success, error) {

		if (!param) {

			param = new Object();
		}
		param.languageType = "zh_CN";
		param.sign = md5(JSON.stringify(param));

		if (url.indexOf("?") > 0) {

			url = url + "&sign=" + param.sign + "&languageType=" + param.languageType;
		} else {

			url = url + "?sign=" + param.sign + "&languageType=" + param.languageType;
		}
		// console.log("进入 request" + "请求地址为:" + process.env.VUE_APP_BASE_API + url + "  请求参数为：" + JSON.stringify(param));
		// console.log(process.env.VUE_APP_BASE_API);
		var result = service({
			url: url,
			method: "post",
			data: param, // 参数
			responseType: 'blob' // 表明返回服务器返回的数据类型
		}).then(response => {
			//resolve(response.data)
			let blob = new Blob([response.data], {
				type: 'application/vnd.ms-excel'
			})
			console.log(blob)
			let fileName = response.headers['content-disposition']
			// 获取文件名
			if (fileName && fileName.length >= 2) {
				fileName = fileName.split('=')[1]
			}
			fileName = decodeURIComponent(fileName);
			if (window.navigator.msSaveOrOpenBlob) {
				console.log(2)
				navigator.msSaveBlob(blob, fileName)
			} else {
				console.log(3)
				var link = document.createElement('a')
				link.href = window.URL.createObjectURL(blob)
				link.download = fileName
				link.click()
				//释放内存
				window.URL.revokeObjectURL(link.href)
			}
		}, error => {

			console.log(error);
		})

		console.log("request，请求返回的结果：" + result);
		return result;
	},
	/**
	 * 基础请求类
	 */
	request: function(url, method, param, success, error) { //正常返回关闭当前页面
		let errorCallback = error
		var requestParam;
		if (!param) {

			requestParam = new Object();
		} else if (param instanceof Array) {
			requestParam = new Object();
			requestParam.list = param;

		} else if (param instanceof Object) {

			requestParam = param

		}
		var userInfo = uni.getStorageSync("userInfo");
		if (userInfo.userCode && userInfo.userCode != "") {
			requestParam.operatorUser = userInfo.userCode;
			requestParam.operatorUserName = userInfo.userName;
			requestParam.languageType = "zh_CN";

		} else {
			requestParam.operatorUser = "notLogin";
			requestParam.operatorUserName = "notLogin";
			requestParam.languageType = "zh_CN";
		}

		requestParam.version = "1.0.1"
		requestParam.sign = md5(JSON.stringify(requestParam));

		if (url.indexOf("?") > 0) {

			url = url + "&sign=" + requestParam.sign + "&languageType=" + requestParam.languageType;
		} else {

			url = url + "?sign=" + requestParam.sign + "&languageType=" + requestParam.languageType;
		}
		console.log("进入 request" + "请求地址为:" + url + "  请求参数为：" + JSON.stringify(
			requestParam));
		// console.log(process.env.VUE_APP_BASE_API);
		var result = service({
			url: url,
			method: method,
			data: requestParam
		}).then(res => {
			console.log(res, "======");
			if (!res.data) {
				uni.showToast({
					title: "请求异常！",
					icon: "none"
				});
				console.log("请求异常" + JSON.stringify(res))
				return;
			}
			if (res.data.success) {

				// console.log("请求返回结果为：" + JSON.stringify(res.data));
				if (success) {

					if (res.data.code === "E00401") {

						//没有更多数据
						uni.showToast({
							title: "当前未登录或已过期，请重新登录！",
							icon: "none"
						})
						var auto = uni.getStorageSync("autoLogin")
						uni.setStorageSync("autoLogin", false);
						// uni.reLaunch({
						// 	url: "/pages/login/login?out=0&auto=" + auto
						// })
						uni.removeStorageSync('token');
						let huazhengData = uni.getStorageSync('huazhengData')
						if(huazhengData){
							location.href = "https://app.hydficqd.com:8082/#/pages/home/home?token" + huazhengData.token +
								'&iv=' + huazhengData.iv + '&account=' + huazhengData.account
						}else{
							uni.showToast({
								icon:'error',
								title:'获取app数据为空'
							})
						}
					} else {
						console.log(res);
						return success(res);
					}

				} else {

					return res.data;
				}
			} else {

				if (error) {
					console.log(error);
					console.log(res);
					return error(res.data);
				} else {
					console.log(111);
					if (res.data.msg && res.data.msg.length > 15) {
						setTimeout(() => {
							uni.showModal({
								content: res.data.msg,
								showCancel: false
							});
						}, 300)
					} else {
						setTimeout(() => {
							uni.showToast({
								title: res.data.msg,
								icon: "none",
								duration: 3000
							});
						}, 300)
					}
				}
			}


		}, error => {

			console.log(error)
			if (error.response && error.response.data && error.response.data.msg && error.response.data
				.msg != "" && (error.response.data.code === 'E00401' || error.response.data.code ===
					'E00402' || error.response.data.code === 'E02202')) { //有返回消息的场合，提示服务器端消息
				if (error.response.data.msg.length > 15) {
					setTimeout(() => {
						uni.showModal({
							content: error.response.data.msg,
							showCancel: false
						});
					}, 300)


				} else {
					setTimeout(() => {
						uni.showToast({
							title: error.response.data.msg,
							icon: "none",
							duration: 3000
						})
					}, 300)
				}
				return
			}
			if (error.response && error.response.status == 401) {
				// uni.reLaunch({
				// 	url: "/pages/login/login"
				// })
				if (errorCallback) {
					errorCallback(error.response.data)
				}
				setTimeout(() => {
					uni.showModal({
						content: error.response.data.msg,
						showCancel: false
					})
				}, 300)
				// uni.showToast({
				// 	title: "当前未登录或已过期，请重新登录！",
				// 	icon: "none"
				// })
				uni.setStorageSync("autoLogin", false);
				uni.removeStorageSync('token');
				let huazhengData = uni.getStorageSync('huazhengData')
				if(huazhengData){
					location.href = "https://app.hydficqd.com:8082/#/pages/home/home?token" + huazhengData.token +
						'&iv=' + huazhengData.iv + '&account=' + huazhengData.account
				}else{
					uni.showToast({
						icon:'error',
						title:'获取app数据为空'
					})
				}


			} else {
				if (error?.response?.data?.msg) {
					setTimeout(() => {
						uni.showModal({
							content: error.response.data.msg,
							showCancel: false
						});
					}, 300)

				} else {
					setTimeout(() => {
						uni.showToast({
							title: error,
							icon: "none",
							duration: 3000
						})
					}, 300)
				}
			}

		})

		// console.log("request，请求返回的结果：" + result);
		return result;
	},

	getResource: function(url) {

		// console.log('commonConstants===>',JSON.stringify(commonConstants))
		// https://192.168.2.211:9002/act/timg.jpg
		return commonConstants.request.imageUrl + url;
		// return requestUrl.baseResUrl + url;
	},
}